package org.com.app.knock.fragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.com.app.knock.KnockApplication;
import org.com.app.knock.activity.FriendActivity;
import org.com.app.knock.view.LoadingView;
import org.com.app.knock.view.SearchFriendItemView;
import org.json.JSONArray;
import org.json.JSONObject;

import z.lib.base.BaseAdapter;
import z.lib.base.BaseItem;
import z.lib.base.BaseServiceCallBack;
import z.lib.base.BaseUtils;
import z.lib.base.BaseView;
import z.lib.base.BaseUtils.API;
import z.lib.base.CommonAndroid;
import z.lib.base.LogUtils;
import z.lib.base.callback.RestClient.RequestMethod;
import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

import com.acv.libs.nbase.BaseFragment;
import com.app.lazyload.ImageLoader2;
import com.knock.app.R;
import com.parse.FindCallback;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;

public class SearchFragment extends BaseFragment implements AnimationListener {
	protected static final String TAG = "SearchFragment";
	private View views;
	ListView listView;
	private BaseAdapter baseAdapter;
	TextView txt_search;
	ArrayList<String> list_result = null;
	private LoadingView loading;
	public static ImageLoader2 imageLoader;
	public SearchFragment() {
		super();
	}

	@Override
	public void setUpFragment(View view) {
		this.views = view;
		CommonAndroid.getView(view, R.id.btn_back).setOnClickListener(this);
		listView =(ListView) views.findViewById(R.id.listview_search);
		CommonAndroid.getView(view, R.id.bt_search).setOnClickListener(this);		
		txt_search = (TextView) views.findViewById(R.id.mTextView1);
		loading = CommonAndroid.getView(view, R.id.loading);
		imageLoader = new ImageLoader2(getActivity());
	}

	@Override
	public int layoytResurce() {
		return R.layout.search;
	}
	
	@Override
	public void onClick(View v) {
		super.onClick(v);
		int idView = v.getId();
		switch (idView) {
		case R.id.btn_back:
//			startFragment(new FriendFragment(), null);
			getActivity().finish();
			break;
		case R.id.bt_search:
			String username_search = txt_search.getText().toString().trim();
//			if(username_search.equals(KnockApplication.userName) || username_search.equals("")){
//				BaseUtils.showDialog(getActivity(), "Information search is invalid!" );
//			}else{
				search2(username_search);
//			}
			InputMethodManager keyboard = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
            keyboard.hideSoftInputFromWindow(v.getWindowToken(), 0);
			break;
		default:
			break;
		}
	}

	private void search2(String username_search) {
		// TODO Auto-generated method stub
		HashMap<String, String> params = new HashMap<String, String>();
		params.put("keyword", username_search);
		BaseUtils.execute(getActivity(), RequestMethod.POST, API.API_FRIEND_SEARCH, params, callback);
	}
	
	private BaseServiceCallBack callback = new BaseServiceCallBack() {

		public void onStart() {
			CommonAndroid.showView(true, loading);
			CommonAndroid.hiddenKeyBoard(getActivity());
		};

		public void onError(String message) {
			CommonAndroid.showView(false, loading);
			if (!isFinish()) {
				LogUtils.e(TAG,"err=="+message);
			}
		};

		public void onSucces(String response) {
			CommonAndroid.showView(false, loading);
			if (!isFinish()) {
				JSONObject mainJsonObject;
				List<BaseItem> baseItems = new ArrayList<BaseItem>();
				baseItems.clear();
				try {
					mainJsonObject = new JSONObject(response);
					JSONArray array = mainJsonObject.getJSONArray("data");
					for(int i =0; i < array.length();i++){
						baseItems.add(new BaseItem(array.getJSONObject(i)));
					}
					LogUtils.e(TAG,mainJsonObject.toString());
					addView(baseItems);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		};
	};

	private void search() {
		// TODO Auto-generated method stub
		String username_search = txt_search.getText().toString().trim();
		ParseQuery<ParseObject> query = ParseQuery.getQuery("DeviceList");
		query.whereEqualTo("area_device", username_search);
		LogUtils.e("score", "Error: ===========");
		query.findInBackground(new FindCallback<ParseObject>() {
		    public void done(List<ParseObject> scoreList, ParseException e) {
		        if (e == null) {
		        	list_result = new ArrayList<String>();
		        	LogUtils.e("score", "Retrieved " + scoreList.size() + " scores");
		            if(scoreList.size() <= 0){
		            	BaseUtils.showDialog(getActivity(), "no data!" );
		            }else{
		            	list_result.clear();
		            	for(int i = 0; i < scoreList.size();i++){
		            		String temp = scoreList.get(i).getString("area_device") + ","+ scoreList.get(i).getString("objectId_device");
		            		list_result.add(temp );
		            	}
		            	addView(null);
		            }
		        } else {
		        	LogUtils.e("score", "Error: " + e.getMessage());
		        }
		    }

		});
		
		
	}
	
	private void addView(List<BaseItem> baseItems) {
		// TODO Auto-generated method stub
/*String[] recourseList=getActivity().getResources().getStringArray(R.array.CountryCodes);
		
        List<BaseItem> baseItems = new ArrayList<BaseItem>();
		baseItems.clear();
		for(int i = 0; i < list_result.size(); i++){
//			LogUtils.e(TAG,"data=="+ list_result.get(i));
			String[] temp = list_result.get(i).split(",");
			JSONObject itemObj = new JSONObject();
		    try
		    {
		    	itemObj.put("area_device", temp[0].trim());
		        itemObj.put("objectId_device", temp[1].trim());
		        baseItems.add(new BaseItem(itemObj));
		    }catch(Exception e){
		    }
		    
		}*/
        
        baseAdapter = new BaseAdapter(getActivity(), new ArrayList<Object>()) {
			@Override
			public BaseView getView(Context context, Object data) {
				final SearchFriendItemView phonecodeListItemView = new SearchFriendItemView(context);
				return phonecodeListItemView;
			}
		};
		baseAdapter.clear();
		baseAdapter.addAllItems(baseItems);
		baseAdapter.notifyDataSetChanged();
		listView.setOnItemClickListener(new OnItemClickListener() {
			@SuppressWarnings("unchecked")
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				BaseUtils.playMedia(getActivity(),R.raw.register);
				BaseItem baseItem = (BaseItem) parent.getItemAtPosition(position);
				
//				String friend_name = baseItem.getString("area_device") +";" +baseItem.getString("objectId_device");
//				if (!KnockApplication.listFriend.contains(friend_name)) {
//					KnockApplication.listFriend.add(friend_name);
//					KnockApplication.savedatafriend(getActivity());
//					KnockApplication.getdatafriend(getActivity());
//				}
				String friend_id = baseItem.getString("id");
				addFriend(friend_id);
		
			}
		});
		
		listView.setAdapter(baseAdapter);
	}

	protected void addFriend(String friend_id) {
		// TODO Auto-generated method stub
		HashMap<String, String> params = new HashMap<String, String>();
		params.put("friend_id", friend_id);
		BaseUtils.execute(getActivity(), RequestMethod.POST, API.API_FRIEND_ADD, params, callbackadd);
	}

	private BaseServiceCallBack callbackadd = new BaseServiceCallBack() {

		public void onStart() {
			CommonAndroid.showView(true, loading);
			CommonAndroid.hiddenKeyBoard(getActivity());
		};

		public void onError(String message) {
			CommonAndroid.showView(false, loading);
			if (!isFinish()) {
				BaseUtils.showDialog(getActivity(),""+message );
			}
		};

		public void onSucces(String response) {
			CommonAndroid.showView(false, loading);
			if (!isFinish()) {
				JSONObject mainJsonObject;
				try {
					mainJsonObject = new JSONObject(response);
					LogUtils.e(TAG,"add+++"+mainJsonObject.toString());
					getActivity().finish();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		};
	};
	
	@Override
	public void onAnimationStart(Animation animation) {

	}

	@Override
	public void onAnimationEnd(Animation animation) {
		mHandle.sendEmptyMessage(0);
	}

	@Override
	public void onAnimationRepeat(Animation animation) {

	}
}